package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.pojo.dto.ConditionListDTO;
import com.xbongbong.paas.pojo.vo.ConditionListVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.score.pojo.dto.DataScoreUpdateBatchDTO;
import com.xbongbong.pro.score.pojo.dto.DataScoreUpdateSingleDTO;
import com.xbongbong.pro.score.pojo.dto.ScoreRabbitMqDTO;
import com.xbongbong.pro.score.pojo.dto.ScoreRangeDetailDTO;
import com.xbongbong.pro.score.pojo.dto.ScoreRangeSaveDTO;
import com.xbongbong.pro.score.pojo.dto.ScoreRuleAddDTO;
import com.xbongbong.pro.score.pojo.dto.ScoreRuleDeleteDTO;
import com.xbongbong.pro.score.pojo.dto.ScoreRuleDetailDTO;
import com.xbongbong.pro.score.pojo.dto.ScoreRuleEnableDTO;
import com.xbongbong.pro.score.pojo.dto.ScoreRuleListDTO;
import com.xbongbong.pro.score.pojo.dto.ScoreRuleSaveDTO;
import com.xbongbong.pro.score.pojo.dto.ScoreScriptLogDTO;
import com.xbongbong.pro.score.pojo.vo.DataScoreUpdateBatchVO;
import com.xbongbong.pro.score.pojo.vo.DataScoreUpdateSingleVO;
import com.xbongbong.pro.score.pojo.vo.ScoreRangeConditionListVO;
import com.xbongbong.pro.score.pojo.vo.ScoreRangeDetailVO;
import com.xbongbong.pro.score.pojo.vo.ScoreRuleListVO;
import com.xbongbong.pro.score.pojo.vo.ScoreRuleSaveVO;
import com.xbongbong.saas.service.ScoreCalculateService;
import com.xbongbong.saas.service.ScoreRangeService;
import com.xbongbong.saas.service.ScoreRuleService;
import com.xbongbong.saas.service.ScoreScriptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author chunyang.qin
 * @Title: 评分控制器
 * @date 2020/11/28:13
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/score")
public class ScoreController {

    private static final Logger LOG = LoggerFactory.getLogger(ScoreController.class);

    @Resource
    private ScoreRuleService scoreRuleService;
    @Resource
    private ScoreRangeService scoreRangeService;
    @Resource
    private ScoreCalculateService scoreCalculateService;
    @Resource
    private ScoreScriptService scoreScriptService;
    @Resource
    private PaasRedisHelper paasRedisHelper;


    /**
     * 评分规则列表
     * @param scoreRuleListDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/rule/list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String list(@RequestBody @Valid ScoreRuleListDTO scoreRuleListDTO, BindingResult br) throws Exception {
        XbbResponse<ScoreRuleListVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ScoreRuleListVO scoreRuleList = scoreRuleService.listScoreRule(scoreRuleListDTO);
                response = new XbbResponse<>(scoreRuleList);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }


    /**
     * 评分规则编辑返显
     * @param
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/rule/add/get", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addGet(@RequestBody @Valid ScoreRuleAddDTO scoreRuleAddDTO, BindingResult br) throws Exception {
        XbbResponse<ScoreRuleSaveVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ScoreRuleSaveVO scoreRuleAddVO = scoreRuleService.getAddVo(scoreRuleAddDTO);
                response = new XbbResponse<>(scoreRuleAddVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 评分规则编辑返显
     * @param scoreRuleDetailDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/rule/update/get", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateGet(@RequestBody @Valid ScoreRuleDetailDTO scoreRuleDetailDTO, BindingResult br) throws Exception {
        XbbResponse<ScoreRuleSaveVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ScoreRuleSaveVO scoreRule = scoreRuleService.getUpdateVo(scoreRuleDetailDTO);
                response = new XbbResponse<>(scoreRule);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }


    /**
     * 评分规则新建，编辑
     * @param scoreRuleSaveDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/rule/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String save(@RequestBody @Valid ScoreRuleSaveDTO scoreRuleSaveDTO, BindingResult br) throws Exception {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);

        } else {
            try {
                // 判断是否跳过重复提交校验
                if (!Boolean.TRUE.equals(scoreRuleSaveDTO.getIgnoreConCheck())) {
                    //重复提交校验
                    if (!paasRedisHelper.checkConcurrentLock(scoreRuleSaveDTO)) {
                        response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                        return JSON.toJSONString(response);
                    }
                }
                TransmittableThreadLocalUtil.setValue(SaasMarkEnum.SAAS.getCode(), scoreRuleSaveDTO.getBusinessType(), scoreRuleSaveDTO.getMenuId(), DistributorMarkEnum.OTHER.getCode());
                BaseVO baseVO = scoreRuleService.saveScoreRule(scoreRuleSaveDTO);
                response = new XbbResponse<>(baseVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }


    /**
     * 评分规则删除
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/rule/delete", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String delete(@RequestBody @Valid ScoreRuleDeleteDTO scoreRuleDelete, BindingResult br) throws Exception {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                // 判断是否跳过重复提交校验
                if (!Boolean.TRUE.equals(scoreRuleDelete.getIgnoreConCheck())) {
                    //重复提交校验
                    if (!paasRedisHelper.checkConcurrentLock(scoreRuleDelete)) {
                        response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                        return JSON.toJSONString(response);
                    }
                }
                BaseVO baseVO = scoreRuleService.deleteScoreRule(scoreRuleDelete);
                response = new XbbResponse<>(baseVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }


    /**
     * 评分规则启用/不启用
     * @param scoreRuleEnableDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/rule/enable", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String sort(@RequestBody @Valid ScoreRuleEnableDTO scoreRuleEnableDTO, BindingResult br) throws Exception {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                // 判断是否跳过重复提交校验
                if (!Boolean.TRUE.equals(scoreRuleEnableDTO.getIgnoreConCheck())) {
                    //重复提交校验
                    if (!paasRedisHelper.checkConcurrentLock(scoreRuleEnableDTO)) {
                        response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                        return JSON.toJSONString(response);
                    }
                }
                BaseVO baseVO = scoreRuleService.enableScoreRule(scoreRuleEnableDTO);
                response = new XbbResponse<>(baseVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 获取评分规则的流转条件
     * @param conditionListDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/rule/condition/list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String listScoreRuleCondition(@RequestBody @Valid ConditionListDTO conditionListDTO, BindingResult br) throws Exception {
        XbbResponse<ConditionListVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ConditionListVO conditionListVO = scoreRuleService.getScoreRuleCondition(conditionListDTO);
                response = new XbbResponse<>(conditionListVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 获取评显示区间的的流转条件
     * @param conditionListDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/range/condition/list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String listScoreRangeCondition(@RequestBody @Valid ConditionListDTO conditionListDTO, BindingResult br) throws Exception {
        XbbResponse<ScoreRangeConditionListVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ScoreRangeConditionListVO scoreRangeCondition = scoreRangeService.getScoreRangeCondition(conditionListDTO);
                response = new XbbResponse<>(scoreRangeCondition);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    @RequestMapping(value = "/range/get", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String listScoreRangeCondition(@RequestBody @Valid ScoreRangeDetailDTO scoreRangeDetailDTO, BindingResult br) throws Exception {
        XbbResponse<ScoreRangeDetailVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ScoreRangeDetailVO scoreRange = scoreRangeService.getScoreRange(scoreRangeDetailDTO);
                response = new XbbResponse<>(scoreRange);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    @RequestMapping(value = "/range/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String listScoreRangeCondition(@RequestBody @Valid ScoreRangeSaveDTO scoreRangeSaveDTO, BindingResult br) throws Exception {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                // 判断是否跳过重复提交校验
                if (!Boolean.TRUE.equals(scoreRangeSaveDTO.getIgnoreConCheck())) {
                    //重复提交校验
                    if (!paasRedisHelper.checkConcurrentLock(scoreRangeSaveDTO)) {
                        response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                        return JSON.toJSONString(response);
                    }
                }
                BaseVO baseVO = scoreRangeService.saveScoreRange(scoreRangeSaveDTO);
                response = new XbbResponse<>(baseVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

//    /**
//     * 更新分数值
//     * @param scoreRangeSaveDTO
//     * @param br
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping(value = "/data/update", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    public String listScoreRangeCondition(@RequestBody @Valid ScoreRabbitMqDTO scoreRabbitMqDTO, BindingResult br) throws Exception {
//        XbbResponse<String> response;
//        if (br.hasErrors()) {
//            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
//            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
//        } else {
//
//                mongoLogHelp.getLoginCount("ding530164324c4938b4",1607011200,1607097599);
//                 return "";
//        }
//        return JSON.toJSONString(response);
//    }

    /**
     * 消费者逻辑
     * @param scoreRabbitMqDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/data/update", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateDataScore(@RequestBody @Valid ScoreRabbitMqDTO scoreRabbitMqDTO, BindingResult br) throws Exception {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                BaseVO baseVO = new BaseVO();
                //todo 消息消费，这里只用于重新计算
                scoreCalculateService.batchDataScoreUpdateForScript(scoreRabbitMqDTO);
                response = new XbbResponse<>(baseVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
            response = new XbbResponse<>();
        }
        return JSON.toJSONString(response);
    }

    /**
     * "重新计算"脚本写入
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/scriptLog/recalculate", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String scriptRecalculate(@RequestBody @Valid ScoreScriptLogDTO scoreScriptLogDTO, BindingResult br) throws Exception {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                BaseVO baseVO = scoreScriptService.saveScoreScript(scoreScriptLogDTO);
                response = new XbbResponse<>(baseVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }



    /**
     * 消费者逻辑
     * @param dataScoreUpdateBatchDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/data/updateBatch", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateDataScore(@RequestBody @Valid DataScoreUpdateBatchDTO dataScoreUpdateBatchDTO, BindingResult br) throws Exception {
        XbbResponse<DataScoreUpdateBatchVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                DataScoreUpdateBatchVO dataScoreUpdateBatchVO = scoreCalculateService.updateBatch(dataScoreUpdateBatchDTO);
                response = new XbbResponse<>(dataScoreUpdateBatchVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
            response = new XbbResponse<>();
        }
        return JSON.toJSONString(response);
    }

    /**
     * 消费者逻辑
     * @param dataScoreUpdateSingleDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/data/updateSingle", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateDataScore(@RequestBody @Valid DataScoreUpdateSingleDTO dataScoreUpdateSingleDTO, BindingResult br) throws Exception {
        XbbResponse<DataScoreUpdateSingleVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                DataScoreUpdateSingleVO dataScoreUpdateSingleVO = scoreCalculateService.updateSingle(dataScoreUpdateSingleDTO);
                response = new XbbResponse<>(dataScoreUpdateSingleVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
            response = new XbbResponse<>();
        }
        return JSON.toJSONString(response);
    }

}
